/**
 * Alipay.com Inc.
 * Copyright (c) 2004-2022 All Rights Reserved.
 */
package com.example.spider.proxy.core.repository;

import com.example.spider.proxy.core.ProxyInfo;
import lombok.extern.slf4j.Slf4j;
import org.redisson.RedissonSortedSet;
import org.redisson.api.RMap;

import java.util.Iterator;

/**
 * redis存储元数据
 *
 * @author lym
 * @see RedissonSortedSet
 */
@Slf4j
public class RedisProxyRepository extends AbstractProxyRepository {

    private final RMap<String, ProxyInfo> repo;// = redisson.getSortedSet("anySet");

    public RedisProxyRepository(RMap<String, ProxyInfo> repo) {
        this.repo = repo;
    }

    @Override
    public Iterator<ProxyInfo> getIterator() {
        return repo.values().iterator();
    }

    @Override
    protected void doAdd(ProxyInfo proxyInfo) {
        repo.put(calculateKey(proxyInfo), proxyInfo);
    }

    @Override
    public ProxyInfo remove(ProxyInfo proxyInfo) {
        repo.remove(calculateKey(proxyInfo));
        return null;
    }

    @Override
    protected int size() {
        return repo.size();
    }

    protected boolean validateAndUpdateProxyInfo(ProxyInfo proxyInfo) {
        boolean result = super.validateAndUpdateProxyInfo(proxyInfo);
        repo.put(calculateKey(proxyInfo), proxyInfo);
        return result;
    }

}